package com.xuexuehai.bkm.service.user.admin.controller;

import com.xuexuehai.bkm.core.common.constants.RespCode;
import com.xuexuehai.bkm.core.common.dto.HttpResp;
import com.xuexuehai.bkm.domain.entity.Admin;
import com.xuexuehai.bkm.security.util.TokenUtil;
import com.xuexuehai.bkm.service.user.admin.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author xuexuehai
 * @mailBox xuehai.xue@QQ.com
 * @date 2021/9/11 2:48 下午
 */
@Api("管理员模块")
@RestController
@RequestMapping("/api/admin")
@Slf4j
public class AdminController {

    @Autowired
    private IAdminService iAdminService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("管理员登录")
    @GetMapping("/login")
    public HttpResp login(String username,String password){
        Admin admin = iAdminService.login(username,password);
        //登录成功

        //规定token在redis缓存中的过期时间，以及在产生时设置Token的有效期 : 10分钟
        Date expireDate = new Date(System.currentTimeMillis() + 1000 * 60 * 10);
        //产生token，并设置有效时间 10分钟
        String token = TokenUtil.getInstance().createToken(admin,expireDate);
        log.info("产生的Token ---> " + token);

        //将token存入Redis缓存，使用String类型的Redis
        stringRedisTemplate.opsForValue()
                .set(token,admin.getNum() + "-" + admin.getPassword());
        //设置缓存存活时间
        stringRedisTemplate.expireAt(token,expireDate);

        return new HttpResp.Builder()
                .code(RespCode.USER_LOGIN_SUCCESS.getCode())
                .msg(RespCode.USER_LOGIN_SUCCESS.getMsg())
                .token(token)
                .times(LocalDateTime.now())
                .results(RespCode.USER_LOGIN_SUCCESS)
                .builder()
                ;
    }

    @ApiOperation("查询所有管理员的信息")
    @GetMapping("/findAllAdmin")
    public HttpResp findAllAdmin(){
        return null;
    }

}
